import { Component, OnInit, OnDestroy } from '@angular/core'
import { Router } from '@angular/router'
import { take } from 'rxjs/operators'
import { NzMessageService } from 'ng-zorro-antd'

import { PageService } from '@shared/services/page.service'
import { RoleService } from '../role.service'
import { INewPageColumn } from '@shared/interfaces/common'
import { IRoleCreateFormData, IRoleUpdate } from '@shared/interfaces/role'
import { ComWindow } from '@shared/classes/ComWindowClass'
import { RoleNewBasicInfoComponent } from './role-new-basic-info/role-new-basic-info.component'
import { RoleNewFunctionsComponent } from './role-new-functions/role-new-functions.component'
import { DataService } from '@shared/services/data.service'
import { I18NService } from '@core'

@Component({
  selector: 'app-role-new',
  templateUrl: './new.component.html',
})
export class RoleNewComponent implements OnInit, OnDestroy {
  pages: INewPageColumn[] = []

  constructor(
    private router: Router,
    private msgSrv: NzMessageService,
    private roleService: RoleService,
    private pageService: PageService,
    private dataService: DataService,
    private i18n: I18NService,
  ) {}

  ngOnInit() {
    this.pages = [
      {
        component: new ComWindow(RoleNewBasicInfoComponent, { title: 'GENERAL.INFO.BASIC' }),
      },
      {
        component: new ComWindow(RoleNewFunctionsComponent, { title: 'ROLE.PERMISSION.TITLE' }),
      },
    ]
  }

  ngOnDestroy(): void {
    this.dataService.setRoleCreateData({})
  }

  submit(formData: IRoleCreateFormData): void {
    const data: IRoleUpdate = {
      roleName: formData.roleName,
      roleType: formData.roleType,
      roleDesc: formData.roleDesc,
      insCodes: [formData.insCode.code],
      menus: formData.functions,
    }
    this.roleService
      .createRole(data)
      .pipe(take(1))
      .subscribe(() => {
        this.pageService.triggerGuardAlive(false)
        this.msgSrv.success(this.trans('GENERAL.NOTIFICATION.CREATE_SUCCESS'))
        this.router.navigate(['/roles/list'])
      })
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
